using System;
using System.IO;
using System.Collections.Generic;
using System.ServiceModel.Web;

namespace TicketSellerService {
	public class FlightTicketService : IFlightTicketService {
	
		public AvailableFlights search( string source, string destination, string date) {
            Console.WriteLine("Handling request trying to search flight from {0} to {1}", source, destination);
			List<Flight> availFlights = new List<Flight>( );
			foreach( Flight flight in TicketsDB.getInstance( ).getFlights( )) {
				if ( flight.source.Equals( source) && flight.destination.Equals( destination) &&
				     flight.date.Equals( Convert.ToDateTime( date))) {
					availFlights.Add( flight);
				}
			}
            if (availFlights.Count == 0)
            {
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound("no flights found");
            }
            else
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Found;
            }
			return new AvailableFlights( availFlights);
		}
		
		public TicketReservation reserve( string flightNumber, string date) {
			TicketReservation reservation = null;
			TicketsDB.getInstance( ).makeReservation( Convert.ToInt32( flightNumber), Convert.ToDateTime( date), out reservation);
            if ( reservation == null)
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.ExpectationFailed;
                WebOperationContext.Current.OutgoingResponse.StatusDescription = String.Format( "Couldn't make reservation for flight {} on date {}", flightNumber, date);
            }
            else
            {
                WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Found;
            }
			return reservation;
		}
		
		public string cancel( string rsrvId) {
			TicketsDB.Status status = TicketsDB.getInstance( ).cancelReservation( Convert.ToInt32(rsrvId));
			if ( status == TicketsDB.Status.CANCELATION_FAILED ) {
                WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound("no reservation found");
				return "Failed, no such reservation";
			}
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Found;
			return "OK";
		}
		
	}
}